import React, { useContext } from 'react'
// import { matchPath } from 'react-router-dom'
import { RouterContext } from '..'

const Switch = (props) => {
  const context = useContext(RouterContext)
  const location = props.location || context.location

  let children, match, lastMatch

  // 遍历匹配，找出最匹配的那一个
  React.Children.forEach(props.children, (child) => {
    const path = child.props.pathname // 获取route上的path
    // child 是组件才会执行
    if (!match && React.isValidElement(child)) {
      // 存放当前匹配到的元素
      children = child
      // 计算是否匹配
      match = path
        ? matchPath(location.pathname, { ...child.props })
        : context.match
    }

    console.log('path ======> ', child)
    if (path == '*') {
      lastMatch = child
    }
    // pathname == * 表示是找不到路由的情况下匹配这个
    
  })

  let Result
  if (match) {
    Result = React.cloneElement(children, { location, computedMatch: match })
  } else {
    console.log("lastMatch =======> ", lastMatch)
    // 有 * 就是用 没有就404
    Result = lastMatch || React.createElement('div', {}, '404')
  }

  return Result
}

export default Switch

function matchPath(path, props) {
  console.log('props ==> pathpathpathpathpathpath ', path)
  console.log('props.pathname == path ===> ', props.pathname == path)
  if (props.pathname == path) {
    return props.component
  }
}
